<?php
// +----------------------------------------------------------------------
// | Wendasns [ 开源问答社区系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020~2021 http://wendasns.com All rights reserved.
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\wendasns\controller;
use app\wendasns\WenBaseController;

use app\wendasns\service\PwArticle;
use app\wendasns\service\PwSeo;
use app\wendasns\service\Srv;
use app\wendasns\model\Article as byArticle;
use app\wendasns\model\Category;
use app\wendasns\model\User;
use app\wendasns\model\Praise;
use app\wendasns\model\Collect;
use app\wendasns\model\Look;
use app\wendasns\model\Comment;
use app\wendasns\model\Reward;
use app\wendasns\model\Seo;
use app\wendasns\model\Reply;
use wendasns\Wend;
use think\Exception;
use think\App;
use think\facade\View;

class Article extends WenBaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    	if(in_array(request()->action(true), ['post','remove','close','collect','reply'])){
    		if(!$this->loginUser->isLogin) error('请登录后再操作',[],['refresh'=>0]);
    	}
    }
	
	//文章列表页
    public function index($cname='all',$type='new',$page=1)
    {
		$limit = configure('page.pageArticle',10);
		$article = new PwArticle();
		$logs = $article->get($type, $limit, $cname, $page);
		$category = Category::where('type', 'article')->select();

		$categoryname = '';
		foreach($category as $v){
			if($v->dir_name==$cname){
				$categoryname = ' - '.$v->name;
			}
		}
		
		$typear = ['new'=>'最新','hot'=>'热门'];
		$pages = $page>1?' - 第'.$page.'页':'';
		
		$data = [
			'category' => $category,
			'logs' => $logs,
			'type' => $type,
			'categoryname' => $cname,
			'top' => []
		];
		$dm = Seo::where('type','article')->find();
		$seo = new PwSeo();
		$seo->title = sprintf('%s%s%s%s',$typear[$type],$dm->title,$categoryname,$pages);
		$seo->description = $dm->description;
		$seo->keywords = $dm->keywords;
		$seo->set();
        return view('index', $data);
    }
    
    //文章详情页
	public function show($id=0, $kid='', $category='')
	{
		if($kid){
			$dm = byArticle::where('kid',$kid)->find();
		}else{
			$dm = byArticle::find($id);
		}
		$limit = input('get.limit',10,'intval');

        if(!$dm || $dm->remove){
            error('文章不存在或已删除');
        }
        
        if($dm->status=='check'){
			if($dm->user_id!==$this->loginUser->uid){
				if(!admin_check('thread.check')){
					error('文章审核中',[],['refresh'=>0]);
				}
			}
        }

		if(!empty($category) && $dm->categorys->dir_name!==$category){
			error('文章不存在或已经失效');
		}
		
        $dm->append(['look']);
        
        $uid = $this->loginUser->uid;

        $dm->withAttr('look',function($value, $data) use ($uid){
        	$res = Look::where([
        		['user_id','=',$uid],
        		['type','=','article'],
        		['target_id','=',$data['id']]
        	])->find();
        	if($res){
        		return 1;
        	}else{
        		if($uid==$data['user_id']){
        			return 1;
        		}else{
        			return 0;
        		}
        		
        	}
        	
        });
        
        //刷新访问量
		$dm->inc('visits')->update();
        
        //关于作者
        $user = $dm->users()->find();
        $user->ask = isset($user->datas->ask)?$user->datas->ask:0;
        $user->article = isset($user->datas->article)?$user->datas->answer:0;
        $user->answer = isset($user->datas->answer)?$user->datas->answer:0;
        $user->adopt = isset($user->datas->adopt)?$user->datas->adopt:0;
        $author = $user;
        
        //相关文章
        $alike = byArticle::where('tags','like',array_map(function($value){return "%$value%";},explode(',',$dm->tags)),'OR')->limit(10)->select();
        
        //收藏
        $dm->iscollect = Collect::where('mold','article')->where('user_id',$this->loginUser->uid)->where('source_id',$dm->id)->find();
        
		$data = [
			'article'=> $dm,
			'alikes' => $alike,
			'author' => $author,
			'comment' => $dm->comments(3)
		];
		$seo = new PwSeo();
		$seo->title = $dm->title;
		$seo->description = substr_format(strip_tags($dm->content),80);
		$seo->keywords = $dm->tags;
		$seo->set();
		View::assign($data);
		event('ArticlePage');
        return View::fetch();
	}
	
	//发布文章
    public function post($id = 0)
    {
    	action_check('article.post');
    	if(request()->isPost()){
    		$this->save();
    	}
    	if($id){
    		$dm = byArticle::find($id);
    		if(!$dm){
    			error('文章不存在或已删除');
    		}
    		$data['article'] = $dm;
    	}
    	
    	//分类数组
    	$data['category'] = Category::where('type', 'article')->select();
		$seo = new PwSeo();
		$seo->title = '发布文章';
		$seo->set();
    	return view('post', $data);
    }
    
    //发布文章
    private function save()
    {
    	$id = input('post.id',0,'intval');
    	$title = input('post.title','');//org\Filter::cleanContent
    	$summary = input('post.summary','');//摘要
    	$content = input('post.content','');
    	$category_id = input('post.category',0,'intval');
    	$tags = input('post.tags','','');
    	$speak = input('post.speak',0,'intval');//禁止评论
    	
    	
    	//数据验证
    	try {
            $this->validate([
                'title'  => $title,
                'content' => $content,
                'tags' => $tags,
                'category' => Category::where('id',$category_id)->where('type','article')->find()
            ],'\app\wendasns\validate\Article');
        } catch (ValidateException $e) {
            error($e->getError());
        }

    	try {
            $article = new PwArticle();
            $article->id = $id;
            $article->user_id = $this->loginUser->uid;
            $article->category_id = $category_id;
            $article->title = $title;
            $article->content = $content;
            $article->summary = $summary;
            $article->tags = $tags;
            $article->speak = $speak;
            $dm = $article->save();
        } catch (\think\Exception $e) {
            error($e->getMessage());
        }
    	success('操作成功', [], ['referer'=>(string)url('wendasns/article/show',$dm)]);
    }
    
    //删除文章
    public function remove()
    {
    	$id = input('post.id',0,'intval');
    	action_check('article.remove');
    	try {
            $article = new PwArticle();
            $article->id = $id;
            $article->remove();
        } catch (\think\Exception $e) {
            error($e->getMessage());
        }
    	success('已删除',[],['referer'=>1]);
    }

    //收藏
    public function collect()
    {
    	if(($dm = $this->article_check()) instanceof Exception){
    		error($dm->getMessage());
    	}
    	$collect = Collect::where('user_id',$this->loginUser->uid)->where('mold','article')->where('source_id',$dm->id)->find();
    	if($collect){
    		error('已收藏');
    	}
    	Collect::create(['user_id'=>$this->loginUser->uid, 'mold'=>'article', 'source_id'=>$dm->id, 'create_time'=>Wend::getTime()]);
    	$dm->inc('collect')->update();
    	$user = User::find($this->loginUser->uid);
    	$user->datas()->inc('collect')->update();
    	success('已收藏');
    }
    
    //点赞
    public function praise()
    {
    	$id = input('post.id',0,'intval');
    	$dm = byArticle::find($id);
    	if(!$dm || $dm->remove){
    		error('文章不存在或已删除');
    	}
    	
        $sql = [
            ['mold','=','article'],
            ['source_id','=',$id],
        ];
        if($this->loginUser->isLogin){
            $sql[] = ['user_id','=',$this->loginUser->uid];
            $user_id = $this->loginUser->uid;
        }else{
            $sql[] = ['ip','=',$this->request->ip()];
            $user_id = 0;
        }
        $praise = Praise::where($sql)->find();
        if($praise){
            error('你已经点过赞了！');
        }
        Praise::create([
            'user_id'=> $user_id,
            'mold' => 'article',
            'source_id' => $dm->id,
            'ip' => $this->request->ip(),
            'create_time' => Wend::getTime()
        ]);
    	
    	$dm->praise = $dm->praise + 1;
    	$dm->save();
    	$dm->users()->find()->datas()->inc('praise')->update();
    	success('谢谢点赞');
    }

    //评论列表
    public function comment()
    {
    	$id = input('get.id',0,'intval');
    	$dm = byArticle::find($id);
    	if(!$dm){
    		return '';
    	}
    	$comment = Comment::where('types','article')->where('source_id',$dm->id)->where('remove',0)->paginate(1);
		
		return view('/comment',['comment'=>$comment]);
    }

    //回复评论
    public function reply()
    {
    	$id = input('post.id',0,'intval');
    	$rid = input('post.rid',0,'intval');
    	$content = input('post.content','');
    	
    	
    	$dm = Reply::create([
    		'user_id' => $this->loginUser->uid,
    		'reply_id' => $rid,
    		'source_id' => $id,
    		'content' => $content,
    	]);
		$html = View::fetch('reply',['item'=>$dm]);
		success('发表成功',['html'=>$html]);
    }
    
    private function article_check()
    {
    	$id = input('post.id', 0, 'intval');
    	$dm = byArticle::find($id);
    	if(!$dm || $dm->remove==1){
    		return new Exception('文章不存在或已删除');
    	}
    	
    	if($dm->status<>'normal'){
    		return new Exception('文章审核中，禁止任何操作');
    	}
    	return $dm;
    }
}
